package vn.com.vega.chacha.v2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.receiver.NetworkStatusReceiver;
import vn.com.vega.music.clientserver.JsonAuth;
import vn.com.vega.music.clientserver.JsonPackage;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.device.FileStorage;
import vn.com.vega.music.objects.Album;
import vn.com.vega.music.objects.Artist;
import vn.com.vega.music.objects.Package;
import vn.com.vega.music.objects.Playlist;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.objects.Video;
import vn.com.vega.music.player.ChaChaProgressDialog;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.ImageDownloader;
import vn.com.vega.music.utils.VegaLog;
import vn.com.vega.music.view.adapter.ListPackageAdapter;
import vn.com.vega.music.view.custom.ChaChaDialog;
import vn.com.vega.music.view.custom.ChaChaDialog.OnCloseDialogListener;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class Appinstant extends Application {
	public static final String GOOGLE_ANALYTIC_UA = "";
	public static boolean isLogin = false;
	public static String warningMessage;
	public static String adMessage;

	// App have funtion trial?
	public static boolean haveTrialFuntion = false;
	public ImageDownloader mImageLoader;
	public List<Object> listSongFeature;
	public List<Object> listVideoFeature;
	public List<Object> listAlbumFeature;
	public List<Object> listPlaylistFeature;
	public List<Object> ListNewsFeature;
	public List<Object> listMusicChartFeature;
	public List<Object> listVideoChartFeature;
	public List<Object> listAlbumChartFeature;

	public HashMap<String, List<Song>> tranportListSong = new HashMap<String, List<Song>>();
	public HashMap<String, List<Video>> tranportListVideo = new HashMap<String, List<Video>>();
	public HashMap<String, Artist> tranportArtis = new HashMap<String, Artist>();
	public HashMap<String, Playlist> tranportPlaylist = new HashMap<String, Playlist>();
	public HashMap<String, Album> tranportAlbum = new HashMap<String, Album>();
	public HashMap<String, String> tranportString = new HashMap<String, String>();
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		VegaLog.e(TAG, "on create");

		NetworkStatusReceiver.networkStatus = NetworkStatusReceiver
				.getNetworkStatus(this);
		mImageLoader = new ImageDownloader();
		listAlbumFeature = new ArrayList<Object>();
		listMusicChartFeature = new ArrayList<Object>();
		listVideoChartFeature = new ArrayList<Object>();
		listAlbumChartFeature = new ArrayList<Object>();
		listPlaylistFeature = new ArrayList<Object>();
		listSongFeature = new ArrayList<Object>();
		listVideoFeature = new ArrayList<Object>();
		ListNewsFeature = new ArrayList<Object>();

		// init some need here
		FileStorage fileStorage = new FileStorage();
		if (DataStore.getInstance() == null) {
			DataStore.init(this);
		}
		// Context appContext = getApplicationContext();
		// mNM = (NotificationManager) appContext
		// .getSystemService(Context.NOTIFICATION_SERVICE);
		// // hideNotification(MusicPlayer.NOTIFY_ID);
	}

	void clearUserData() {
		if (listSongFeature != null) {
			listSongFeature.clear();
		}
		if (listVideoFeature != null) {
			listVideoFeature.clear();
		}
		if (listAlbumFeature != null) {
			listAlbumFeature.clear();
		}
		if (listPlaylistFeature != null) {
			listPlaylistFeature.clear();
		}
		if (ListNewsFeature != null) {
			ListNewsFeature.clear();
		}
		if (listMusicChartFeature != null) {
			listMusicChartFeature.clear();
		}
		if (listVideoChartFeature != null) {
			listVideoChartFeature.clear();
		}
		if (listAlbumChartFeature != null) {
			listAlbumChartFeature.clear();
		}
		tranportAlbum.clear();
		tranportArtis.clear();
		tranportListSong.clear();
		tranportListVideo.clear();
		tranportPlaylist.clear();
		tranportString.clear();
	}

	private static final String TAG = "ChaChaAppInstant";

	public static boolean canTrialFuntion() {
		// For now alway return false
		return false;
	}

	/**
	 * Call when register new package
	 * 
	 * @param ctx
	 * @param jsonAuth
	 * @param handler
	 * @param haveTrial
	 *            true if have option trial
	 */
	public void register(final Context ctx, final String message,
			final Handler handler, final boolean haveTrial,
			/*final View.OnClickListener closeClickListener, */final RegisterListener registerListener) {
		// Show message dialog before register.
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				final ChaChaDialog dialog = new ChaChaDialog(ctx, null);
				dialog.setTitle(ctx.getString(R.string.dilog_title_default));
				dialog.setMessage(message);
				final ChaChaProgressDialog progressDialog = new ChaChaProgressDialog(ctx);
				View.OnClickListener okClickListener = new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Thread getListPackages = new Thread() {
							@Override
							public void run() {
								getListPackage(ctx, handler, progressDialog,
										haveTrial, registerListener);
								dialog.dismiss();
							}
						};
						getListPackages.start();
					}
				};
				dialog.addButton("Đăng ký", okClickListener);

				if (canTrialFuntion() && haveTrial) {
					View.OnClickListener trialClickListener = new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							dialog.dismiss();

							Thread registerTrial = new Thread() {
								@Override
								public void run() {
									// doRegisterTrial(ctx, handler,
									// progressDialog);
									registerTrial(ctx, handler, progressDialog,
											false);
								}
							};
							registerTrial.start();
						}
					};
					dialog.addButton("Dùng thử", trialClickListener);
				}

				if (message != null && message != "") {
					dialog.show();
				} else {
					Thread getListPackages = new Thread() {
						@Override
						public void run() {
							getListPackage(ctx, handler, progressDialog,
									haveTrial, registerListener);
						}
					};
					getListPackages.start();
				}
			}
		});
	}

	private void getListPackage(final Context ctx, final Handler handler,
			final ChaChaProgressDialog progressDialog, final boolean haveTrial,
			final RegisterListener registerListener) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog.setMessage(ctx
						.getText(R.string.login_screen_load_package));
				progressDialog.show();
			}
		});

		final JsonPackage listPackage = JsonPackage.loadPackageList();
		Runnable getListPackageFail = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog.dismiss();
				final ChaChaDialog dialog = new ChaChaDialog(ctx, null);
				dialog.setTitle(ctx.getString(R.string.dilog_title_default));
				dialog.setMessage(ctx
						.getString(R.string.login_screen_no_package));
				View.OnClickListener okClickListener = new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
//						RegisterListener register = (RegisterListener) ctx;
//						register.onRegisterFailListener();
					}
				};
				dialog.addButton("OK", okClickListener);
				dialog.show();
			}
		};
		Runnable getListPackageSuccess = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog.dismiss();
				if (listPackage.packages.size() > 1) {
					showListpackage(ctx, handler, listPackage.packages,
							haveTrial, registerListener);
				} else if (listPackage.packages.size() == 1) {
					showSMSDialog(ctx, handler, listPackage.packages,
							listPackage.packages.get(0), haveTrial,
							registerListener);
				}

			}
		};

		if (listPackage.isSuccess() && listPackage.packages.size() >= 1) {
			// Get list package success!
			handler.post(getListPackageSuccess);

		} else {
			// Get list package fail!
			handler.post(getListPackageFail);
		}

	}

	private void showListpackage(final Context ctx, final Handler handler,
			final ArrayList<Package> listPackage, final boolean haveTrial,
			final RegisterListener registerListener) {
		final ChaChaDialog dialogViewList = new ChaChaDialog(ctx, null);
		dialogViewList.setTitle("Chọn gói dịch vụ");
		dialogViewList.hideBottomView();
		ListView listPackages = new ListView(ctx);
		ListPackageAdapter adapter = new ListPackageAdapter(listPackage, ctx);
		listPackages.setAdapter(adapter);
		AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Package select = listPackage.get(position);
				DataStore dataStore = DataStore.getInstance();
				if (dataStore.getConfig(Const.KEY_PACKAGE_CODE)
						.equalsIgnoreCase(select.code)) {
					Toast.makeText(ctx, "Bạn đã đăng ký gói cước này",
							Toast.LENGTH_SHORT).show();
				} else {
					showSMSDialog(ctx, handler, listPackage, select, haveTrial,
							registerListener);
					dialogViewList.dismiss();
				}
			}
		};
		listPackages.setOnItemClickListener(onItemClickListener);
		dialogViewList.setContentView(listPackages);
		dialogViewList.show();
	}

	private void showSMSDialog(final Context ctx, final Handler handler,
			final ArrayList<Package> listPackages, final Package selected,
			final boolean haveTrial,
			final RegisterListener registerListener) {
		final ChaChaDialog dialog = new ChaChaDialog(ctx, null);
		dialog.setTitle("Xác nhận");
		String newLine = System.getProperty("line.separator");
		String message = "Đăng kí gói cước " + selected.name + " ("
				+ selected.price + ")" + newLine + newLine + selected.name
				+ " - " + selected.description + newLine + newLine
				+ "Gửi tin nhắn với nội dung " + "'" + selected.smsContent
				+ "' đến '" + selected.smsServer + "' để đăng kí dịch vụ";
		dialog.setMessage(message);
		dialog.hideCloseDefaultBtn();

		View.OnClickListener cancelClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				if (listPackages.size() > 1) {
					showListpackage(ctx, handler, listPackages, haveTrial,
							registerListener);
				} else {
					if (registerListener != null) {
						registerListener.onRegisterFailListener();
					}
				}

			}
		};

		View.OnClickListener confirmClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				sendSMS(ctx, selected.smsServer, selected.smsContent);
//				final ChaChaProgressDialog progressDialog = new ChaChaProgressDialog(
//						ctx);
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						doRegister(selected, ctx, handler, progressDialog, registerListener);
//					}
//				}).start();
			}
		};
		// View.OnClickListener trialClickListener = new View.OnClickListener()
		// {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// final ChaChaProgressDialog progressDialog = new
		// ChaChaProgressDialog(ctx);
		// Thread registerTrialThread = new Thread() {
		// @Override
		// public void run() {
		// // doRegisterTrial(ctx, handler, progressDialog);
		// registerTrial(ctx, handler, progressDialog, false);
		// }
		// };
		// registerTrialThread.start();
		// }
		// };

		dialog.addButton("Đồng ý", confirmClickListener);
		// if (canTrialFuntion() && haveTrial) {
		// dialog.addButton("Dùng thử", trialClickListener);
		// }
		dialog.addButton("Hủy", cancelClickListener);

		dialog.show();
	}

	private void sendSMS(Context ctx, String phoneNumber, String message) {
		// call message composer
		Uri uri = Uri.parse("smsto:" + phoneNumber);
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		it.putExtra("sms_body", message);
		ctx.startActivity(it);
	}

	private void doRegister(Package selected, final Context ctx,
			Handler handler, final ChaChaProgressDialog progressDialog, final RegisterListener registerListener) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog
						.setMessage(getString(R.string.login_screen_registering));
				progressDialog.setCancelable(false);
				progressDialog.show();
			}
		});

		Runnable hideprogress = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog.dismiss();
			}
		};
//		final RegisterListener registerListener = (RegisterListener) ctx;
		DataStore dataStore = DataStore.getInstance();
		// Nhan dang thue bao
		JsonAuth jsons = JsonAuth.identify();
		if (jsons.isSuccess()) {
			String packagecode = jsons.packageCode.trim();
			// Chua dang ky goi cuoc hoac dang ky goi cuoc
			// moi
			if (packagecode.equalsIgnoreCase("")
					|| (!packagecode.equals("") && !packagecode
							.equals(selected.code))) {
				final JsonAuth jsonAuths = JsonAuth.subscribe(selected.code,
						jsons.phoneNumber);
				if (!jsonAuths.isSuccess()) {
					handler.post(hideprogress);
					if (!isNotEmtyString(jsonAuths.getErrorMessage())) {
						handler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								final ChaChaDialog messageDialog = new ChaChaDialog(
										ctx, null);
								messageDialog.setTitle(ctx
										.getString(R.string.dilog_title_default));
								messageDialog.setMessage(jsonAuths
										.getErrorMessage());
								messageDialog.hideCloseDefaultBtn();
								View.OnClickListener clickListener = new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										messageDialog.dismiss();
										if (registerListener != null) {
											registerListener.onRegisterFailListener();
										}
												
									}
								};
								messageDialog.addButton("OK", clickListener);
								messageDialog.show();
							}
						});
					} else {
						if (registerListener != null) {
							registerListener.onRegisterFailListener();
						}
						sendSMS(ctx, selected.smsServer, selected.smsContent);
					}
				} else {
					// success
					if (jsonAuths.username != null)
						dataStore.setMsisdn(jsonAuths.phoneNumber);
					if (jsonAuths.password != null)
						dataStore.setPassword(jsonAuths.password);
					if (selected.price != null)
						dataStore.setPrice(selected.price);
					handler.post(hideprogress);
					registerListener.onRegisterSuccessListener();
				}
			} else {
				// Da dang ky va trung goi cuoc
				handler.post(hideprogress);
				handler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ChaChaDialog dialog = new ChaChaDialog(ctx, null);
						dialog.setMessage(ctx
								.getString(R.string.subcribe_duplicated_package));
						dialog.setTitle(ctx
								.getString(R.string.dilog_title_default));
						dialog.addDefaultOkBtn("OK");
						dialog.show();
					}
				});
			}
		} else {
			// Nhan dang khong thanh cong
			// Thu lay so dien thoai
			TelephonyManager tMgr = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			String mPhoneNumber = tMgr.getLine1Number();
			if (mPhoneNumber != null && !mPhoneNumber.equals("")) {
				// Neu lay duoc
				final JsonAuth jsonauth = JsonAuth.subscribe(selected.code,
						mPhoneNumber);
				if (jsonauth.isSuccess()) {
					if (jsonauth.username != null)
						dataStore.setMsisdn(jsonauth.phoneNumber);
					if (jsonauth.password != null)
						dataStore.setPassword(jsonauth.password);
					if (selected.price != null)
						dataStore.setPrice(selected.price);
					handler.post(hideprogress);
					registerListener.onRegisterSuccessListener();
				} else {
					handler.post(hideprogress);
					if (!isNotEmtyString(jsonauth.getErrorMessage())) {
						handler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								final ChaChaDialog messageDialog = new ChaChaDialog(
										ctx, null);
								messageDialog.setTitle(ctx
										.getString(R.string.dilog_title_default));
								messageDialog.setMessage(jsonauth
										.getErrorMessage());
								messageDialog.hideCloseDefaultBtn();
								View.OnClickListener clickListener = new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										messageDialog.dismiss();
										registerListener
												.onRegisterFailListener();
									}
								};
								messageDialog.addButton("OK", clickListener);
								messageDialog.show();
							}
						});
					} else {
						registerListener.onRegisterFailListener();
						sendSMS(ctx, selected.smsServer, selected.smsContent);
					}
				}
			} else {
				// Neu khong lay duoc
				// Gui SMS
				handler.post(hideprogress);
				registerListener.onRegisterFailListener();
				sendSMS(ctx, selected.smsServer, selected.smsContent);
			}
		}
	}

	/*
	 * private void confirmSMSTrial (final Context ctx, Handler handler) {
	 * handler.post(new Runnable() {
	 * 
	 * @Override public void run() { // TODO Auto-generated method stub final
	 * ChaChaDialog confirmSMS = new ChaChaDialog(ctx);
	 * confirmSMS.setTitle(ctx.getString(R.string.dilog_title_default));
	 * DataStore dataStore = DataStore.getInstance(); final String trialSMSMsg =
	 * dataStore.getConfig(Const.KEY_TRIAL_SMS_CONTENT); final String
	 * trialSMSServer = dataStore.getConfig(Const.KEY_TRIAL_SMS_SERVER);
	 * confirmSMS.setMessage(String.format(
	 * ctx.getString(R.string.confirm_register_trial_message), trialSMSMsg,
	 * trialSMSServer)); final RegisterListener registerListener =
	 * (RegisterListener) ctx; View.OnClickListener yesClick = new
	 * View.OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub confirmSMS.dismiss(); registerListener.onRegisterFailListener();
	 * sendSMS(ctx, trialSMSServer, trialSMSMsg); } }; View.OnClickListener
	 * noClick = new View.OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub confirmSMS.dismiss(); registerListener.onRegisterFailListener(); }
	 * }; confirmSMS.addButton(ctx.getString(R.string.confirm_yes), yesClick);
	 * confirmSMS.addButton(ctx.getString(R.string.confirm_no), noClick);
	 * confirmSMS.hideCloseDefaultBtn(); confirmSMS.show(); } }); }
	 */
	public void registerTrial(final Context ctx, final Handler handler,
			final ChaChaProgressDialog progressDialog, boolean needConfirm) {
		if (needConfirm) {
			final DataStore dataStore = DataStore.getInstance();
			handler.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					final ChaChaDialog offRequest = new ChaChaDialog(ctx, null);
					offRequest.setTitle(ctx.getString(R.string.register_trial));
					offRequest.setMessage(String.format(
							ctx.getString(R.string.confirm_register_trial_message),
							dataStore.getConfig(Const.KEY_TRIAL_SMS_CONTENT),
							dataStore.getConfig(Const.KEY_TRIAL_SMS_SERVER)));
					View.OnClickListener yesClickListener = new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							if (offRequest != null && offRequest.isShowing()) {
								offRequest.dismiss();
							}
							doRegisterTrial(ctx, handler, progressDialog);
						}
					};

					View.OnClickListener noClickListener = new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (offRequest != null && offRequest.isShowing()) {
								offRequest.dismiss();
								RegisterListener registerListener = (RegisterListener) ctx;
								registerListener.onRegisterFailListener();
							}
						}
					};

					offRequest.addButton(ctx.getString(R.string.confirm_yes),
							yesClickListener);
					offRequest.addButton(ctx.getString(R.string.confirm_no),
							noClickListener);
					offRequest.hideCloseDefaultBtn();
					offRequest.show();
				}
			});
		} else {
			doRegisterTrial(ctx, handler, progressDialog);
		}
	}

	public void doRegisterTrial(final Context ctx, final Handler handler,
			final ChaChaProgressDialog progressDialog) {

		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog
						.setMessage(getString(R.string.doing_register_trial));
				progressDialog.setCancelable(false);
				progressDialog.show();
			}
		});

		final Runnable hideProgress = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog.dismiss();
			};
		};
		final RegisterListener registerListener = (RegisterListener) ctx;
		DataStore dataStore = DataStore.getInstance();
		// Nhan dang thue bao
		JsonAuth jsons = JsonAuth.identify();
		if (jsons.isSuccess()) {
			final JsonAuth jsonAuths = JsonAuth
					.registerTrial(jsons.phoneNumber);
			if (!jsonAuths.isSuccess()) {
				handler.post(hideProgress);
				if (isNotEmtyString(jsonAuths.getErrorMessage())) {
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							final ChaChaDialog messageDialog = new ChaChaDialog(
									ctx, null);
							messageDialog.setTitle(ctx
									.getString(R.string.dilog_title_default));
							messageDialog.setMessage(jsonAuths
									.getErrorMessage());
							messageDialog.hideCloseDefaultBtn();
							View.OnClickListener clickListener = new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									messageDialog.dismiss();
									registerListener.onRegisterFailListener();
								}
							};
							messageDialog.addButton("OK", clickListener);
							messageDialog.show();
						}
					});
				} else {
					// confirmSMSTrial(ctx, handler);
					registerListener.onRegisterFailListener();
					sendSMS(ctx,
							dataStore.getConfig(Const.KEY_TRIAL_SMS_SERVER),
							dataStore.getConfig(Const.KEY_TRIAL_SMS_CONTENT));
				}
			} else {
				// success
				if (jsonAuths.username != null)
					dataStore.setMsisdn(jsonAuths.phoneNumber);
				if (jsonAuths.password != null)
					dataStore.setPassword(jsonAuths.password);
				if (jsonAuths.message != null
						&& !jsonAuths.message.equalsIgnoreCase("")) {
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							handler.post(hideProgress);
							final ChaChaDialog dialog = new ChaChaDialog(ctx,
									null);
							dialog.setTitle("Thông báo");
							dialog.setMessage(jsonAuths.message);
							View.OnClickListener clickListener = new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									registerListener
											.onRegisterSuccessListener();
								}
							};
							dialog.addButton("Ok", clickListener);
							dialog.hideCloseDefaultBtn();
							dialog.show();
						}
					});
				} else {
					handler.post(hideProgress);
					registerListener.onRegisterSuccessListener();
				}
			}
		} else {
			// Nhan dang khong thanh cong
			// Thu lay so dien thoai
			TelephonyManager tMgr = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			String mPhoneNumber = tMgr.getLine1Number();
			if (mPhoneNumber != null && !mPhoneNumber.equals("")) {
				// Neu lay duoc
				final JsonAuth jsonauth = JsonAuth.registerTrial(mPhoneNumber);
				if (jsonauth.isSuccess()) {
					if (jsonauth.username != null)
						dataStore.setMsisdn(jsonauth.phoneNumber);
					if (jsonauth.password != null)
						dataStore.setPassword(jsonauth.password);
					// registerListener.onRegisterSuccessListener();
					if (jsonauth.message != null
							&& !jsonauth.message.equalsIgnoreCase("")) {
						handler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								handler.post(hideProgress);
								final ChaChaDialog dialog = new ChaChaDialog(
										ctx, null);
								dialog.setTitle("Thông báo");
								dialog.setMessage(jsonauth.message);
								View.OnClickListener clickListener = new OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										dialog.dismiss();
										registerListener
												.onRegisterSuccessListener();
									}
								};
								dialog.addButton("Ok", clickListener);
								dialog.show();
							}
						});
					} else {
						handler.post(hideProgress);
						registerListener.onRegisterSuccessListener();
					}

				} else {
					handler.post(hideProgress);
					if (!isNotEmtyString(jsonauth.getErrorMessage())) {
						handler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								final ChaChaDialog messageDialog = new ChaChaDialog(
										ctx, null);
								messageDialog.setTitle(ctx
										.getString(R.string.dilog_title_default));
								messageDialog.setMessage(jsonauth
										.getErrorMessage());
								messageDialog.hideCloseDefaultBtn();
								View.OnClickListener clickListener = new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										messageDialog.dismiss();
										registerListener
												.onRegisterFailListener();
									}
								};
								messageDialog.addButton("OK", clickListener);
								messageDialog.show();
							}
						});
					} else {
						// confirmSMSTrial(ctx, handler);
						registerListener.onRegisterFailListener();
						sendSMS(ctx, dataStore
								.getConfig(Const.KEY_TRIAL_SMS_SERVER),
								dataStore
										.getConfig(Const.KEY_TRIAL_SMS_CONTENT));
					}
				}
			} else {
				// Neu khong lay duoc
				// Gui SMS
				handler.post(hideProgress);
				// confirmSMSTrial(ctx, handler);
				registerListener.onRegisterFailListener();
				sendSMS(ctx, dataStore.getConfig(Const.KEY_TRIAL_SMS_SERVER),
						dataStore.getConfig(Const.KEY_TRIAL_SMS_CONTENT));
			}
		}
	}

	interface RegisterListener {
		public void onRegisterSuccessListener();

		public void onRegisterFailListener();
	}

	public static boolean isNotEmtyString(String str) {
		if (str == null) {
			return false;
		}

		if (str.equalsIgnoreCase("")) {
			return false;
		}
		return true;
	}

	public void cleanApp() {
		VegaLog.e(TAG, "Start clean app");
		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		try {
			mImageLoader.clearCache();
			mImageLoader = null;
		} catch (Exception e) {
			// TODO: handle exception
		}
//		try {
//
//			if (DownloadManager.isRunning()) {
//				DownloadManager.stopDownload();
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}
//		try {
//			if (SynchronizeManager.isRunning()) {
//				SynchronizeManager.stopSyncThread();
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}

		DataStore.uninit();

		// try {
		// if (ImageLoader.getInstance(getApplicationContext()) != null) {
		// ImageLoader.getInstance(getApplicationContext()).release();
		// }
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		// }
		// }).start();
	}

	public void showListRingtone(Context ctx, String songname) {
		Intent intent = new Intent(ctx, RingtoneScreen.class);
		intent.putExtra(RingtoneScreen.KEY_RINGTONE_NAME, songname);
		ctx.startActivity(intent);
	}

}
